package com.colin.jipay.nxys.helper;

import android.app.Activity;
import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Message;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.colin.jipay.activity.MainActivity;
import com.colin.jipay.nxys.NxysMainActivity;
import com.colin.jipay.utils.AbSharedUtil;
import com.colin.jipay.utils.CallbackListener;
import com.colin.jipay.utils.GsonUtils;
import com.colin.jipay.utils.JSONUtil;
import com.colin.jipay.utils.SimpleTaskSuccess;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.TimeUnit;

import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.XposedHelpers;

public class NxysHelper {

    public static Context context;
    public static ClassLoader classLoader;
    private static String url = "http://nxt.nongxinyin.com/fvp-qp/qp.do?reqJson=";

    private static Activity reciveAmtActivity;
    public static Object objApplication;


    public static final String ACTION_CONNECT = "com.nxys.socket.ACTION_CONNECT";
    public static final String ACTION_NOTIFI = "com.nxys.socket.ACTION_NOTIFI";
    public static final String ACTION_NOTIFI_NEW = "com.nxys.socket.ACTION_NOTIFI_NEW";
    public static final String CHECK_ORDER = "com.nxys.chexk";

    /**
     * 主动调用生成二维码的方法
     */
    public static void callCreateQrCode(String money, CallbackListener<String> callbackListener) throws Exception {
        try {
            LogUtils.i("主动调用生成二维码的方法");
            Class requestUtils = getRequestUtils();
            Object objRequestParams = XposedHelpers.callStaticMethod(
                    XposedHelpers.findClass("com.buybal.buybalpay.util.RequestUtils", classLoader)
                    , "getReciveAmt"
                    , objApplication
                    , getEncry(objApplication)
                    , XposedHelpers.callStaticMethod(
                            XposedHelpers.findClass("com.buybal.framework.utils.AmountUtils"
                                    , classLoader)
                            , "yesAmt"
                            , money)
                    , "3");
            getNetReq(objRequestParams, callbackListener);
        } catch (Exception e) {
            StringBuilder sb = new StringBuilder();
            sb.append("eeee >>>>>>>>> ");
            sb.append(e.fillInStackTrace());
            XposedBridge.log(sb.toString());
        }
    }

    /**
     * hook到创建二维码的方法被调用
     *
     * @param classLoader
     */
    public static void hookGetQrLink(final ClassLoader classLoader) {
        XposedHelpers.findAndHookMethod("com.buybal.buybalpay.activity.ReciveAmtActivity"
                , classLoader
                , "getQrlink"
                , String.class
                , String.class
                , new XC_MethodHook() {
                    @Override
                    protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
                        super.beforeHookedMethod(param);
                        LogUtils.i("hook到了二维码的创建的方法", param.args[0], param.args[1]);
                        if (reciveAmtActivity == null) {
                            LogUtils.i("reciveAmtActivity为null,进行初始化操作");
                            reciveAmtActivity = (Activity) param.thisObject;
                            context = (Activity) param.thisObject;
                            objApplication = XposedHelpers.getObjectField(context, "app");
                            NxysHelper.classLoader = classLoader;
                        }
                    }
                });

        XposedHelpers.findAndHookMethod("com.buybal.buybalpay.bean.ResponseparamsQrlink"
                , classLoader
                , "getCodeUrl"
                , new XC_MethodHook() {
                    @Override
                    protected void afterHookedMethod(MethodHookParam param) throws Throwable {
                        super.afterHookedMethod(param);
                        LogUtils.i("hook到从二维码bean类里面getCodeUrl的方法", param.getResult() + "");
                    }
                });

    }

    /**
     * 注册农信易扫的广播接收器，只要在homeActivity被创建的时候注册就好
     *
     * @param context
     */
    public static void registNxysReceiver(Context context) {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ACTION_CONNECT);
        intentFilter.addAction(CHECK_ORDER);
        context.registerReceiver(new MyBroadcastReceiver(), intentFilter);
    }

    /**
     * 模拟农信易扫的网络请求
     *
     * @param obj 加密的参数
     */
    private static void getNetReq(Object obj, final CallbackListener<String> callbackListener) {
        try {
            StringBuilder sb = new StringBuilder();
            sb.append("");
            sb.append(obj);
            String encode = URLEncoder.encode(URLEncoder.encode(sb.toString(), "utf-8"), "utf-8");
            StringBuilder sb2 = new StringBuilder();
            sb2.append(url);
            sb2.append(encode);
            LogUtils.i("请求参数：" + sb2.toString());
            OkGo.<String>post(sb2.toString()).execute(new StringCallback() {
                @Override
                public void onSuccess(Response<String> response) {
                    callbackListener.success(response.body());
                }

                @Override
                public void onError(Response<String> response) {
                    super.onError(response);
                    callbackListener.error(response.body());
                }
            });
        } catch (UnsupportedEncodingException e) {
            LogUtils.i(e.getMessage());
        }
    }

    /**
     * 获取所有的订单信息
     *
     * @param
     */
    public static void getalltrade() {
        LogUtils.i("开始执行获取所有订单数据任务");
        if (objApplication == null) {
            XposedBridge.log("登录信息为空");
            return;
        }
        Object objRequestParams = XposedHelpers.callStaticMethod(
                XposedHelpers.findClass("com.buybal.buybalpay.util.RequestUtils", classLoader)
                , "getAllstoreLsit"
                , objApplication
                , getEncry(objApplication)
                , "10006");
        getNetReq(objRequestParams, new CallbackListener<String>() {
            @Override
            public void error(String str) {

            }

            @Override
            public void success(String str) {
                LogUtils.i(str);
                NxysAllOrderBean allOrderBean = GsonUtils.fromJson(str, NxysAllOrderBean.class);
                List<NxysAllOrderBean.StoreListBean> storeListBeans = allOrderBean.getStoreList();
                for (int i = 0; i < storeListBeans.size(); i++) {
                    final NxysAllOrderBean.StoreListBean storeBean = storeListBeans.get(i);
                    ThreadUtils.executeByCpuWithDelay(new SimpleTaskSuccess<Object>() {
                        @Override
                        public void onSuccess(Object result) {
                            getDayTrade(storeBean.getShopId(), storeBean.getLoginId());
                        }
                    }, 3, TimeUnit.SECONDS);
                }
            }
        });
    }

    /**
     * 循环执行获取订单列表的任务
     *
     * @param thisObject
     */
    public static void scheduleGetOrdersTask(final Context thisObject) {
        ThreadUtils.executeByFixedAtFixRate(4, new SimpleTaskSuccess<Object>() {
            @Override
            public void onSuccess(Object result) {
                getalltrade();
            }
        }, 3, TimeUnit.SECONDS);
    }

    /**
     * 获取该商铺下的当日订单交易记录
     *
     * @param shopId
     * @param loginId
     */
    public static void getDayTrade(final String shopId, final String loginId) {
        LogUtils.i("开始获取当日的交易记录");
        Object objRequestParams = XposedHelpers.callStaticMethod(
                XposedHelpers.findClass("com.buybal.buybalpay.util.RequestUtils", classLoader)
                , "getstoreOrdeLsit"
                , objApplication
                , getEncry(objApplication)
                , "10008"
                , shopId
                , loginId
                , TimeUtils.date2String(TimeUtils.getNowDate(), "yyyy-MM-dd")
                , "1"
                , "15"
        );
        LogUtils.i("getDayTrade请求参数objRequestParams=" + objRequestParams);
        getNetReq(objRequestParams, new CallbackListener<String>() {
            @Override
            public void error(String str) {

            }

            @Override
            public void success(String str) {
                LogUtils.i("日交易订单数据 shopId=" + shopId, str);
                NxysShopOrderBean shopOrderBean = GsonUtils.fromJson(str, NxysShopOrderBean.class);
                List<NxysShopOrderBean.OrderListBean> newOrdersAndSave = getNewOrdersAndSave(shopOrderBean, shopId, loginId);
                LogUtils.i("获取到的新交易数据量为：" + newOrdersAndSave.size(), GsonUtils.toJson(newOrdersAndSave));
                Intent intent=new Intent("com.nxys.getNewOrder");
                intent.putExtra("orders",GsonUtils.toJson(newOrdersAndSave));
                ((Application)objApplication).sendBroadcast(intent);
            }
        });
    }

    /**
     * 处理获取到的单个商铺下的订单数据
     *
     * @param shopOrderBean 取到该商铺下的最新的15条订单数据
     * @param shopId
     * @param loginId
     * @return 返回比本地保存的最新订单id更加新的数据列表
     */
    private static List<NxysShopOrderBean.OrderListBean> getNewOrdersAndSave(NxysShopOrderBean shopOrderBean, String shopId, String loginId) {
        //保存的sp文件名用loginId_shopId来表示不同的账号下的不同商铺的订单数据
        String lastOrderId = SPUtils.getInstance(loginId + "_" + shopId).getString("orderId", "");
        List<NxysShopOrderBean.OrderListBean> orderListBeans = shopOrderBean.getOrderList();
        List<NxysShopOrderBean.OrderListBean> newOrderBeans = new ArrayList<>();
        for (int i = 0; i < orderListBeans.size(); i++) {
            NxysShopOrderBean.OrderListBean orderBean = orderListBeans.get(i);
            String orderId = orderBean.getOrderId();
            //保存商铺下订单列表里面的第一条消息
            if (i == 0) {
                SPUtils.getInstance(loginId + "_" + shopId).put("orderId", orderId);
            }

            if (!lastOrderId.equals(orderId)) {
                newOrderBeans.add(orderBean);
            } else {
                break;
            }
        }
        return newOrderBeans;

    }

    private static Object getEncry(Object obj) {
        return XposedHelpers.callMethod(XposedHelpers.newInstance(XposedHelpers.findClass("com.buybal.buybalpay.util.RequestNetutils", classLoader), obj), "getEncruManager", new Object[0]);
    }

    private static Class<?> getRequestUtils() {
        return XposedHelpers.findClass("com.buybal.buybalpay.util.RequestUtils", classLoader);
    }


    private static class MyBroadcastReceiver extends BroadcastReceiver {
        private MyBroadcastReceiver() {
        }

        public void onReceive(final Context context, Intent intent) {
            String stringExtra;
            String stringExtra2;
            //接收到要创建二维码的消息
            if (intent.getAction().equals(ACTION_CONNECT)) {
                stringExtra = intent.getStringExtra("money");
                stringExtra2 = intent.getStringExtra("mark");
                if (stringExtra == null) {
                    stringExtra = "0.01";
                }
                if (stringExtra2 == null) {
                    stringExtra2 = "测试";
                }
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append("money =");
                stringBuilder.append(stringExtra);
                stringBuilder.append("mark=");
                stringBuilder.append(stringExtra2);
                XposedBridge.log(stringBuilder.toString());
                final String finalStringExtra = stringExtra;
                final String finalStringExtra1 = stringExtra2;
//                GenQrCode(finalStringExtra, finalStringExtra1);
                try {
                    callCreateQrCode(stringExtra, new CallbackListener<String>() {
                        @Override
                        public void error(String str) {
                            XposedBridge.log(str);
                        }

                        @Override
                        public void success(String str) {
                            LogUtils.i("网络请求获取二维码结果" + str);
                            JSONObject js = new JSONObject();
                            JSONUtil.setString(js, "reqPayUrl", str);
                            //通过webSocket服务，把请求的付款的url发送给服务端
//                            if (NxysMainActivity.socketBinder != null) {
//                                NxysMainActivity.socketBinder.send(js);
//                            }
                            //下面这个是适配jiPay这个应用的webSocket统一的长连接
                            if (MainActivity.mWebService != null) {
                                //MainActivity.mWebService.send(js.toString());
                                OkGo.<String>post(AbSharedUtil.getString(context, "url")+"/channel/common/plugin/app/alipayrx/class/uppayurl")
                                        .upJson(js.toString())
                                        .execute(new StringCallback() {
                                            @Override
                                            public void onSuccess(Response<String> response) {
                                                LogUtils.i("发送农信易扫二维码数据到服务端了");
                                            }
                                        });
                            }
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (intent.getAction().equals(CHECK_ORDER)) {
                XposedBridge.log("收到");
                stringExtra = intent.getStringExtra("name");
                stringExtra2 = intent.getStringExtra("title");
                final String finalStringExtra2 = stringExtra;
                final String finalStringExtra3 = stringExtra2;
                new Thread(new Runnable() {
                    public void run() {
//                        String CheckNewOrder = CheckNewOrder(finalStringExtra2, finalStringExtra3);
                        String CheckNewOrder = "";
                        String str = "";
                        String str2 = "";
                        if (!(CheckNewOrder == null || "".equals(CheckNewOrder))) {
                            try {
                                JSONObject parseObject = JSONUtil.getJSONObject(CheckNewOrder);
                                String string = parseObject.getString("orderDetail");
                                CheckNewOrder = parseObject.getString("orderId");
                                if (string != null) {
                                    try {
                                        if (!"".equals(string)) {
                                            str = JSONUtil.getJSONObject(string).optString("postScript");
                                        }
                                    } catch (Exception unused) {
                                    }
                                }
                                str2 = CheckNewOrder;
                            } catch (Exception unused2) {
                            }
                        }
                        Message message = new Message();
                        message.what = 1;
                        StringBuilder stringBuilder = new StringBuilder();
                        stringBuilder.append("收到扫码转账：name");
                        stringBuilder.append(finalStringExtra2);
                        stringBuilder.append("   title:");
                        stringBuilder.append(finalStringExtra3);
                        stringBuilder.append("  mark:");
                        stringBuilder.append(str);
                        message.obj = stringBuilder.toString();
//                        handler.sendMessage(message);
//                        httpPost(str, str2, finalStringExtra3);
                    }
                }).start();
            }
        }
    }
}
